/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.applicationResource;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.common.util.ConvertUtil;
import com.blandware.atleap.model.core.ApplicationResource;
import com.blandware.atleap.model.core.ContentLocale;
import com.blandware.atleap.service.core.ApplicationResourceManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.ApplicationResourceForm;
import com.blandware.atleap.webapp.util.core.LocaleUtil;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>Prepares form bean to update application resource's data
 * </p>
 * <p><a href="CallUpdateApplicationResourceAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.7 $ $Date: 2007/12/11 14:23:45 $
 * @struts.action name="applicationResourceForm"
 * path="/core/applicationResource/callUpdate"
 * scope="request"
 * validate="false"
 * roles="core-applicationResource-update"
 * @struts.action-forward name="updateApplicationResource"
 * path=".core.applicationResource.update"
 * @struts.action-forward name="listApplicationResources"
 * path="/core/applicationResource/list.do"
 * redirect="true"
 */
public final class CallUpdateApplicationResourceAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

		if ( isCancelled(request) ) {
			return mapping.findForward("listApplicationResources");
		}

		ApplicationResourceForm applicationResourceForm = (ApplicationResourceForm) form;
		String key = applicationResourceForm.getKey();
		if ( GenericValidator.isBlankOrNull(key) ) {
			if ( request.getAttribute(WebappConstants.APPLICATION_RESOURCE_KEY_KEY) != null ) {
				key = (String) request.getAttribute(WebappConstants.APPLICATION_RESOURCE_KEY_KEY);
			} else {
				if ( log.isWarnEnabled() ) {
					log.warn("Missing application resource ID. Returning to list...");
				}
				return mapping.findForward("listApplicationResources");
			}
		}
		ApplicationResourceManager applicationResourceManager = (ApplicationResourceManager) getBean(Constants.APPLICATION_RESOURCE_MANAGER_BEAN);
		List availableLocales = LocaleUtil.getInstance(servlet.getServletContext()).getEnabledLocales();
		for ( int i = 0; i < availableLocales.size(); i++ ) {
			ContentLocale locale = (ContentLocale) availableLocales.get(i);
			String localeIdentifier = locale.getIdentifier();
			ApplicationResource applicationResource = applicationResourceManager.retrieveApplicationResource(key, localeIdentifier);
			if ( applicationResource != null ) {
				applicationResourceForm.setValue(localeIdentifier, ConvertUtil.convertToString(applicationResource.getValue()));
				applicationResourceForm.setVersion(localeIdentifier, applicationResource.getVersion());
			}
		}

		if ( applicationResourceForm.getValueMap().isEmpty() ) {
			// action page not found. it might be deleted by someone else
			ActionMessages errors = new ActionMessages();
            errors.add("applicationResourceNotFound", new ActionMessage("core.applicationResource.errors.notFound", key));
			saveErrors(request, errors);
			return mapping.findForward("listApplicationResources");
		}

		request.getSession().setAttribute(WebappConstants.CONTENT_LOCALES_COLLECTION_KEY, availableLocales);

		// save transaction token in request
		saveToken(request);
		return mapping.findForward("updateApplicationResource");
	}

}